package com.cn.wanxi.servlet.product;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ProdudctModel;
import com.cn.wanxi.service.IProductService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.util.ImgUpload;
import com.cn.wanxi.util.Tool;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet("/backimg/product/add")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 0，乱码
         * 1.拿到页面的数据
         * 2.封装数据对象--model
         * 3.调用service
         * 4.得到返回数据，反馈
         * 5.将得到的数据返回给前端
         * 6.因为前端是用json对象进行传输，所以后台必须以json对象传递给前台
         *
         */
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        只有图片上传时才在这里做是否已经登录，因为req只能用一次，
//        如果在过滤器用了，这里是没有值的
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");
        JSONObject jsonObject = new JSONObject();
        if (username == null) {
            jsonObject.put("result", -1);
        } else {
            ImgUpload.upload(req);
            //        1.拿到页面的数据
            String productName = (String) req.getAttribute("productName");
            String imgHref = (String) req.getAttribute("imgHref");
            String marketPrice = (String) req.getAttribute("marketPrice");
            String normalPrice = (String) req.getAttribute("normalPrice");
            String content = (String) req.getAttribute("content");
            String cusineId = (String) req.getAttribute("cuisineId");
            ProdudctModel produdctModel = new ProdudctModel();
            produdctModel.setProductName(productName);
            produdctModel.setImgHref(imgHref);
            produdctModel.setMarketPrice(Tool.stringToFloat(marketPrice));
            produdctModel.setNormalPrice(Tool.stringToFloat(normalPrice));
            produdctModel.setContent(content);
            produdctModel.setCusineId(Tool.stringToInt(cusineId));
            IProductService iProductService = new ProductServiceImpl();
            String result = iProductService.add(produdctModel);
            jsonObject.put("result", result);
        }
        resp.getWriter().println(jsonObject);

    }
}
